import { Component, OnInit, Input, Output, EventEmitter, ViewChild, ElementRef, HostBinding } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor, NgForm, FormGroup, FormControl } from '@angular/forms';
import * as dayjs from 'dayjs';

@Component({
	selector: 'm-timing',
	templateUrl: './timing.component.html',
	styleUrls: ['./timing.component.scss'],
	providers: [
		{
			provide: NG_VALUE_ACCESSOR,
			multi: true,
			useExisting: TimingComponent,
		},
	],
})
export class TimingComponent implements OnInit, ControlValueAccessor {
	@Input() required = true;
	@Input()
	formGroup = new FormGroup({
		date: new FormControl(''),
		time: new FormControl(''),
	});
	blue: () => void;
	constructor() {}
	ngOnInit() {}

	writeValue(value: any): void {
		const day = dayjs(value);
		if (!day.isValid()) {
			return;
		}
		const date = day.format('YYYY-MM-DD');
		const time = day.format('HH:mm');
		this.formGroup.setValue({ date, time });
	}
	registerOnChange(fn: any): void {
		this.formGroup.valueChanges.subscribe(() => {
			const { date, time } = this.formGroup.value;
			if (date && time) {
				fn(dayjs(`${date} ${time}`).toDate());
			} else {
				fn(null);
			}
		});
	}
	registerOnTouched(fn: any): void {
		this.blue = fn;
	}
}
